package org.example.securevideotransmission.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.example.securevideotransmission.model.VideoProcessor;

import java.io.File;

public class MainController {
    @FXML
    private TextField secretVideoPath;
    @FXML
    private TextField originalVideoPath;
    private Stage primaryStage; // 不使用 @FXML 注解，因为这个是通过代码动态设置的

    @FXML
    private void onSelectSecretVideo() {
        if (primaryStage == null) {
            showAlert("错误", "主窗口未正确初始化！");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择涉密视频");
        File file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            secretVideoPath.setText(file.getAbsolutePath());
        }
    }

    @FXML
    private void onSelectOriginalVideo() {
        if (primaryStage == null) {
            showAlert("错误", "主窗口未正确初始化！");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择原素材视频");
        File file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            originalVideoPath.setText(file.getAbsolutePath());
        }
    }

    @FXML
    private void onEncryptClicked() {
        String secretPath = secretVideoPath.getText();
        String originalPath = originalVideoPath.getText();

        if (secretPath == null || secretPath.isEmpty() || originalPath == null || originalPath.isEmpty()) {
            showAlert("错误", "请同时选择涉密视频和原素材视频！");
            return;
        }

        try {
            // 确保输出目录存在
            File outputDir = new File("output");
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }

            VideoProcessor.processVideos(secretPath, originalPath, "output/final_video.mp4");
            showAlert("成功", "视频融合完成！输出文件位于 output/final_video.mp4");
        } catch (Exception e) {
            showAlert("错误", "处理视频时出错：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public void setPrimaryStage(Stage stage) {
        this.primaryStage = stage;
    }
}
